import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Vector;
import java.util.Iterator;
import java.io.StringReader;

import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.document.Document;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.util.Version;;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.queryParser.MultiFieldQueryParser;

public class Main
{
    public static void main(String[] argv)
    {
        try
        {
            String field = "multifield";
            BufferedReader reader = new BufferedReader(new FileReader(new File("../docs.txt")));
            BufferedWriter writer = new BufferedWriter(new FileWriter(new File("../docs." + field)));
            String temp;
            Unit unit = new Unit();
            DocUnit docunit = new DocUnit();
            int flag = 0;
            int count = 0;
            while ((temp = reader.readLine()) != null)
            {
                if (temp.isEmpty())
                {
                    count++;
                    // Construct a RAMDirectory to hold the in-memory representation
                    // of the index.
                    RAMDirectory idx = new RAMDirectory();
                    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);
                    IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_31, analyzer);
                    iwc.setOpenMode(OpenMode.CREATE);

                    // Make an writer to create the index
                    IndexWriter indexwriter = new IndexWriter(idx, iwc);
                    Iterator iter = unit.docs.iterator();
                    while (iter.hasNext())
                    {
                        DocUnit d = (DocUnit)iter.next();
                        indexwriter.addDocument(createDocument(d.def, d.example, d.words));
                    }
                    // Optimize and close the writer to finish building the index
                    indexwriter.optimize();
                    indexwriter.close();
                    // Build an IndexSearcher using the in-memory index
                    IndexSearcher searcher = new IndexSearcher(idx);
                    Query query;
                    // Search the query
                    if (!field.equals("multifield"))
                    {
                        QueryParser parser = new QueryParser(Version.LUCENE_31, field, analyzer);
                        query = parser.parse(unit.name);
                    }
                    else
                    {
                        query = MultiFieldQueryParser.parse(Version.LUCENE_31, new String[] {unit.name,unit.name,unit.name},   new String[] {"definition","example","words"}, analyzer);
                    }
                    TopDocs results = searcher.search(query, 100);
                    ScoreDoc[] hits = results.scoreDocs;
                    int numTotalHits = results.totalHits;
                    // Output the result
                    writer.write(unit.name + "\n");
                    writer.write("total docs:" + unit.docs.size() + "  hit: " +  numTotalHits + "\n");
                    for (int i = 0; i < numTotalHits; ++i)
                    {
                        Document doc = searcher.doc(hits[i].doc);
                        String content = new String();
                        if (!field.equals("multifield"))
                        {
                            content = doc.get(field);
                        }
                        else
                        {
                            content = "\n@definition@: " + doc.get("definition") + "\n@example@: " + doc.get("example") + "\n@words@: " + doc.get("words");
                        }
                        writer.write((i + 1) + ". score=" + hits[i].score + "   " + content + "\n");
                    }
                    writer.newLine();
                    unit.name = "";
                    unit.docs.clear();
                    continue;
                }
                if (unit.name.isEmpty())
                {
                    unit.name = temp;
                    continue;
                }
                String t = temp.substring(temp.indexOf(':') + 1);
                if (flag == 0)
                {
                    docunit = new DocUnit();
                    docunit.def = t;
                    flag++;
                }
                else if (flag == 1)
                {
                    docunit.example = t;
                    flag++;
                }
                else
                {
                    docunit.words = t;
                    flag = 0;
                    unit.docs.add(docunit);
                }
            }
            System.out.println(count);
            reader.close();
            writer.close();
        }
        catch (Exception ex)
        {
            System.out.println(ex.getMessage());
        }
    }

    private static Document createDocument(String def, String example, String words)
    {
        Document doc = new Document();
        doc.add(new Field("definition", def, Field.Store.YES, Field.Index.ANALYZED));
        doc.add(new Field("example", example, Field.Store.YES, Field.Index.ANALYZED));
        doc.add(new Field("words", words, Field.Store.YES, Field.Index.ANALYZED));
        return doc;
    }
}
